<template>
  <div>

    <div style="text-align:left" v-if="flg.searchFlg">
      <el-form :inline="true" :model="queryCondition" class="demo-form-inline">
        <el-form-item label="权限名称" style="font-weight: bold">
          <el-input v-model="queryCondition.key" placeholder="权限名称" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="状态" style="font-weight: bold">
          <el-select v-model="queryCondition.isDelete" prop="isDelete" size="mini">
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getPermissionList" size="mini">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作列表 -->
    <el-row style="margin-bottom:10px">
      <el-col :span="12" style="text-align:left">

        <el-button type="danger" icon="el-icon-minus" size="mini" plain @click="batchUpdateStatus('0')"
          v-show="!flg.batchDeleteFlg">批量停用</el-button>
        <el-button type="danger" icon="el-icon-minus" size="mini" plain @click="batchDelete()"
          v-show="flg.batchDeleteFlg">批量删除</el-button>

        <el-button type="warning" icon="el-icon-check" size="mini" plain @click="batchUpdateStatus('1')"
          v-show="flg.batchDeleteFlg">批量恢复</el-button>

        <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="clickDialog('insert')">新增</el-button>

        <el-button type="info" icon="el-icon-upload" size="mini" plain @click="dialog.dialogDownloadVisible = true">导入
        </el-button>
      </el-col>
      <el-col :span="12" style="text-align:right">
        <el-tooltip class="item" effect="dark" :content="flg.searchFlg ? '隐藏搜索' : '展开搜索'" placement="top">
          <el-button icon="el-icon-search" size="mini" circle @click="flg.searchFlg = !flg.searchFlg"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button icon="el-icon-refresh" size="mini" circle @click="getPermissionList"></el-button>
        </el-tooltip>
      </el-col>
    </el-row>
    <!-- 操作列表 -->

    <!-- 权限列表 -->
    <el-table :data="permissionData" stripe style="width: 100%" @selection-change="handleSelectionChange"
      v-loading="flg.loadingFlg">
      <el-table-column type="selection" width="45">
      </el-table-column>
      <el-table-column prop="id" label="序号" width="75">
        <template slot-scope="scope">
          <span>{{ (queryCondition.pageSize - 1) * queryCondition.pageNum + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="permissionKey" label="权限名称" width="510">
      </el-table-column>
      <el-table-column prop="permissionSort" label="排序" width="75">
      </el-table-column>
      <el-table-column prop="isDelete" label="状态" width="75">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.isDelete == 0 ? '正常' : '停用'" placement="top">
            <el-switch :value="scope.row.isDelete == 0 ? true : false" active-color="#13ce66" inactive-color="#ff4949"
              @change="batchUpdateStatus(scope.row.isDelete, scope.row.id)">
            </el-switch>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="权限描述" width="510">
        <template slot-scope="scope">
          <el-input type="textarea" v-model="scope.row.remark" :readonly="true"></el-input>
        </template>
      </el-table-column>

      <el-table-column prop="creator" label="创建人" width="150">
      </el-table-column>
      <el-table-column prop="createDate" label="创建时间" width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="modifier" label="修改人" width="150">
      </el-table-column>
      <el-table-column prop="modifyDate" label="修改时间" width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.modifyDate) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="75">
        <template slot-scope="scope">
          <button type="button" v-show="scope.row.isDelete == 1" @click="batchDelete(scope.row.id)"
            class="el-button el-button--text el-button--mini">
            <i class="el-icon-edit">
              <span>彻底删除</span>
            </i>
          </button>

          <button type="button" v-show="scope.row.isDelete == 0" @click="clickDialog('update', scope.row.id)"
            class="el-button el-button--text el-button--mini">
            <i class="el-icon-edit">
              <span>修改</span>
            </i>
          </button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 权限列表 -->

    <!--    分页框-->
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryCondition.pageSize" :page-sizes="[10, 20, 50, 100, 10000]" :page-size="queryCondition.pageNum"
        layout="total, sizes, prev, pager, next, jumper" :total="queryCondition.pageTotal">
      </el-pagination>
    </div>
    <!--    分页框-->

    <!--    新增/修改 模态框-->
    <el-dialog :title="dialog.dialogTitle" :visible.sync="dialog.dialogFormVisible" width="40%" :append-to-body="true">
      <el-form :model="permissionForm" :rules="rules" ref="permissionForm" label-width="100px">

        <el-form-item label="权限名称" prop="permissionKey">
          <el-input v-model="permissionForm.permissionKey" size="small"></el-input>
        </el-form-item>

        <el-form-item label="显示顺序">
          <el-input-number v-model="permissionForm.permissionSort" size="small" :min="1" :max="100"></el-input-number>
        </el-form-item>

        <el-form-item label="权限描述">
          <el-input type="textarea" v-model="permissionForm.remark" size="small"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('permissionForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!--    新增/修改 模态框-->

    <!-- 批量添加 模态框 -->
    <el-dialog title="导入权限" :visible.sync="dialog.dialogDownloadVisible" width="30%" :append-to-body="true">
      <el-upload class="upload-demo" name="permissionFile" ref="upload" action="uploadFile.url" drag accept=".xlsx, .xls"
        multiple :limit="1" :auto-upload="false" :http-request="uploadFile" style="text-align:center">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          仅允许导入xls、xlsx格式文件。<span class="el-link--inner" @click="downloadFileTempleate">下载模板</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.dialogDownloadVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 批量添加 模态框 -->

  </div>
</template>

<script>
import alter from '@/js/axios'
import {
  requestPermissionLimit, requestPermissionInert, requestPermissionSelectById,
  requestPermissionUpdate, requestBatchUpdatePermissionIsDelete, requestBatchDeletePermissionById,
  requestPermissionUploadTemplates, requestPermissionDownlodaTemplates
} from '@/js/api/permission'
export default {
  name: "permissionIndex",
  data() {
    return {
      permissionData: [],
      multipleSelectionId: [],//多选的id
      //查询条件
      queryCondition: {
        pageSize: 1,//查询第几页
        pageNum: 10,//一页显示多少行
        key: "",
        isDelete: "0",
        pageTotal: 0,//数据总数
      },
      flg: {
        loadingFlg: true,
        searchFlg: true,
        batchDeleteFlg: true
      },
      permissionForm: {
        id: "",
        permissionKey: "",
        permissionSort: "",
        remark: ""
      },
      dialog: {
        dialogFormVisible: false,
        dialogTitle: "",
        dialogDownloadVisible: false
      },
      //表单校验规则
      rules: {
        //菜单名称
        permissionKey: [
          { required: true, message: "请输入权限名称", trigger: 'blur' },
          { min: 2, max: 18, message: '长度在 2 到 40 个字符', trigger: 'blur' }
        ]
      },
    }
  },
  created() {
    this.flg.loadingFlg = true
    this.getPermissionList()
  },
  methods: {
    //处理多选（批量停用\删除）
    handleSelectionChange(val) {
      this.multipleSelectionId = []
      val.forEach(element => {
        this.multipleSelectionId.push(element.id)
      });
    },
    handleSizeChange(val) {
      //  修改一页显示条数
      this.queryCondition.pageNum = val
      this.getPermissionList()
    },
    handleCurrentChange(val) {
      //修改页数
      this.queryCondition.pageSize = val
      this.getPermissionList()
    },
    //点击显示新增/修改模态框
    clickDialog(type, id) {
      if (type == "insert") {
        this.dialog.dialogTitle = "新增权限"
        if (this.permissionForm.id != "") {
          this.reset()
        }
      } else if (type == "update") {
        this.dialog.dialogTitle = "修改权限"
        this.permissionForm.id = id
        this.selectPermissionById()
      }
      this.dialog.dialogFormVisible = true
    },
    //重置表单
    reset() {
      this.permissionForm = {
        id: "",
        permissionKey: "",
        permissionSort: "",
        remark: ""
      };
      this.$refs['permissionForm'].resetFields();
    },
    //点击确认表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialog.dialogFormVisible = false
          //true:添加菜单 false修改菜单
          if (this.permissionForm.id == "") {
            this.insertPermission()
          } else {
            this.updatePermission()
          }
        } else {
          return false;
        }
      })
    },
    //确认批量添加
    submitUpload() {
      this.$refs.upload.submit();
    },
    //覆盖默认的上传行为
    uploadFile(param) {
      const File = param.file;
      let formData1 = new FormData();
      formData1.append("permissionFile", File);
      this.uploadPermissionTemplates(formData1)
    },
    //上传模板
    uploadPermissionTemplates(data) {
      return requestPermissionUploadTemplates(data).then(() => {
        this.getPermissionList()
        this.$refs.upload.clearFiles();
        this.dialog.dialogDownloadVisible = false
      })
    },
    //下载文件模板
    downloadFileTempleate() {
      requestPermissionDownlodaTemplates().then(res => {
        const link = document.createElement('a')
        const blob = new Blob([res.data])
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', `导入权限模板.xlsx`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    },
    //通过id查询权限
    selectPermissionById() {
      let data = {
        id: this.permissionForm.id
      }
      requestPermissionSelectById(data).then(res => {
        let data = res.data.data
        this.permissionForm = {
          id: data.id,
          permissionKey: data.permissionKey,
          permissionSort: data.permissionSort,
          remark: data.remark
        };
      })
    },
    //点击批量删除
    batchDelete(id) {
      this.$confirm("删除后将不可恢复，谨慎操作！！！", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          ids: id
        }
        //如果id为空，代表执行的是批量操作
        if (id == undefined || id == "") {
          if (this.multipleSelectionId.length == 0) {
            alter.errorMessage("未选择数据！")
            return
          }
          //重新给ids赋值
          data = {
            ids: this.multipleSelectionId.toString(),
          }
        }
        requestBatchDeletePermissionById(data).then(() => {
          this.getPermissionList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //批量修改权限状态 停用、恢复
    batchUpdateStatus(val, id) {
      let title = val == 0 ? "停用后将不再显示！" : "是否确认启用。"
      this.$confirm(title + ' 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          ids: id,
          isDelete: val == 0 ? 1 : 0
        }

        if (id == undefined || id == "") {
          if (this.multipleSelectionId.length == 0) {
            alter.errorMessage("未选择数据！")
            return
          }
          //重新给ids赋值
          data.ids = this.multipleSelectionId.toString()
        }

        requestBatchUpdatePermissionIsDelete(data).then(() => {
          this.getPermissionList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //新增权限
    insertPermission() {
      let data = {
        permissionKey: this.permissionForm.permissionKey,
        permissionSort: this.permissionForm.permissionSort,
        remark: this.permissionForm.remark,
      }
      requestPermissionInert(data).then(() => {
        this.getPermissionList()
        this.reset()
      })
    },
    //修改权限
    updatePermission() {
      requestPermissionUpdate(this.permissionForm).then(() => {
        this.getPermissionList()
        this.reset()
      })
    },
    //获取权限列表
    getPermissionList() {
      this.flg.loadingFlg = true
      if (this.queryCondition.isDelete == 0) {
        this.flg.batchDeleteFlg = false
      } else {
        this.flg.batchDeleteFlg = true
      }
      let data = {
        pageSize: this.queryCondition.pageSize,
        pageNum: this.queryCondition.pageNum,
        key: this.queryCondition.key,
        delete: this.queryCondition.isDelete
      }
      requestPermissionLimit(data).then(res => {
        let permissionData = res.data.data
        this.permissionData = permissionData.list
        this.queryCondition.pageTotal = permissionData.size
        this.flg.loadingFlg = false
      })
    },

  }
}
</script>

<style scoped></style>